import Vue from 'vue'
import Router from 'vue-router'
import store from '../vuex'
import {clearvuex} from "../vuex/clear";
import {message,getLocalStorage,delLocalStorage} from '../common/util'

import IndexPage from '@/pages/index'
import LoginPage from '@/pages/login'
import SettingPage from '@/pages/setting'
import PasswordPage from '@/pages/password'
import SubscribeManagerPage from '@/pages/subscribeManager'
import AddSubscribePage from '@/pages/subscribeManager/addSubscribe'
import HolidayPartyListPage from '@/pages/subscribeManager/holidayPartyList'
import HolidayPartyDetailPage from '@/pages/subscribeManager/holidayPartyDetail'
import ToPayDepositPage from '@/pages/subscribeManager/toPayDeposit'
import SubscribeDetailPage from '@/pages/subscribeManager/subscribeDetail'
import DepositTermPage from '@/pages/subscribeManager/depositTerm'
import OrderDetailPage from '@/pages/subscribeManager/orderDetail'
import PresentManagerPage from '@/pages/presentManager'
import ChoosePresentPage from '@/pages/presentManager/choosePresent'
import SubmitPresentPage from '@/pages/presentManager/submitPresent'
import PresentedListPage from '@/pages/presentManager/presentedList'
import PresentDetailPage from '@/pages/presentManager/presentDetail'
import PresentStatisticsPage from '@/pages/presentManager/presentStatistics'
import NoticeIndexPage from '@/pages/notice'
import CallServicesListPage from '@/pages/notice/callServicesList'
import CallServicesDetailPage from '@/pages/notice/callServicesDetail'
import RequestPresentListPage from '@/pages/notice/requestPresentList'
import RequestPresentDetailPage from '@/pages/notice/requestPresentDetail'
import RequestCardListPage from '@/pages/notice/requestCardList'
import RequestCardDetailPage from '@/pages/notice/requestCardDetail'
import RequestKeepListPage from '@/pages/notice/requestKeepList'
import RequestKeepDetailPage from '@/pages/notice/requestKeepDetail'
import NormalNoticeListPage from '@/pages/notice/normalNoticeList'
import NormalNoticeDetailPage from '@/pages/notice/normalNoticeDetail'
import DistributeSubscribePage from '@/pages/todaySubscribe/distributeSubscribe'
import TodaySubscribeListPage from '@/pages/todaySubscribe'
import SubscribePerformancePage from '@/pages/subscribePerformance'
import ManagerManagerPage from '@/pages/managerManager'
import NowAreaStatusPage from '@/pages/managerManager/nowAreaStatus'
import NowSaleStatusPage from '@/pages/managerManager/nowSaleStatus'
import TurnOverListPage from '@/pages/managerManager/turnOverList'

Vue.use(Router)

const router = new Router({
  //mode:'history',//网址没有了#号，hBuilder打包成APP不能使用，需要注释
  base: '/sales/',
  routes: [
    {
      path: '/login',
      name: '登录',
      component: LoginPage
    },
    {
      path: '/password',
      name: '重置密码',
      component: PasswordPage
    },
    {
      path: '/',
      name: '主页',
      component: IndexPage,
      meta:{requireAuth: true }
    },
    {
      path: '/setting',
      name: '设置',
      component: SettingPage,
      meta:{requireAuth: true }
    },
    {
      path: '/subscribeManager',
      name: '客户预订管理',
      component: SubscribeManagerPage,
      meta:{requireAuth: true, module:['subscribeManager'] }
    },
    {
      path: '/addSubscribe/:subscribe',
      name: '增加预订',
      component: AddSubscribePage,
      meta:{requireAuth: true, module:['subscribeManager'] }
    },
    {
      path: '/holidayPartyList',
      name: '节日/派对列表',
      component: HolidayPartyListPage,
      meta:{requireAuth: true, module:['subscribeManager'] }
    },
    {
      path: '/holidayPartyDetail/:holidayPartyId',
      name: '节日/派对详情',
      component: HolidayPartyDetailPage,
      meta:{requireAuth: true, module:['subscribeManager'] }
    },
    {
      path: '/toPayDeposit/:subscribeId',
      name: '订金支付',
      component: ToPayDepositPage,
      meta:{requireAuth: true, module:['subscribeManager'] }
    },
    {
      path: '/subscribeDetail/:subscribeId/:type',
      name: '预订详情',
      component: SubscribeDetailPage,
      meta:{requireAuth: true, module:['subscribeManager'] }
    },
    {
      path: '/depositTerm',
      name: '预订协议',
      component: DepositTermPage,
      meta:{requireAuth: true, module:['subscribeManager'] }
    },
    {
      path: '/orderDetail/:orderId',
      name: '订单详情',
      component: OrderDetailPage,
      meta:{requireAuth: true, module:['presentManager','notice','subscribeManager'] }
    },
    {
      path: '/presentManager',
      name: '当前可赠送列表',
      component: PresentManagerPage,
      meta:{requireAuth: true, module:['presentManager'] }
    },
    {
      path: '/choosePresent/:type/:orderId',
      name: '选择要赠送商品',
      component: ChoosePresentPage,
      meta:{requireAuth: true, module:['presentManager'] }
    },
    {
      path: '/submitPresent/:type/:orderId',
      name: '提交赠送',
      component: SubmitPresentPage,
      meta:{requireAuth: true, module:['presentManager'] }
    },
    {
      path: '/presentedList',
      name: '赠送酒水查询',
      component: PresentedListPage,
      meta:{requireAuth: true, module:['presentManager'] }
    },
    {
      path: '/presentDetail/:presentId',
      name: '赠送酒水详情',
      component: PresentDetailPage,
      meta:{requireAuth: true, module:['presentManager'] }
    },
    {
      path: '/presentStatistics',
      name: '赠送查询统计',
      component: PresentStatisticsPage,
      meta:{requireAuth: true, module:['presentManager'] }
    },
    {
      path: '/noticeIndex',
      name: '消息通知',
      component: NoticeIndexPage,
      meta:{requireAuth: true, module:['notice'] }
    },
    {
      path: '/callServicesList',
      name: '呼叫服务列表',
      component: CallServicesListPage,
      meta:{requireAuth: true, module:['notice'] }
    },
    {
      path: '/callServicesDetail/:callServiceId',
      name: '呼叫服务详情',
      component: CallServicesDetailPage,
      meta:{requireAuth: true, module:['notice'] }
    },
    {
      path: '/requestPresentList',
      name: '赠送请求审批列表',
      component: RequestPresentListPage,
      meta:{requireAuth: true, module:['notice'] }
    },
    {
      path: '/requestPresentDetail/:presentId',
      name: '赠送请求审批详情',
      component: RequestPresentDetailPage,
      meta:{requireAuth: true, module:['notice'] }
    },
    {
      path: '/requestCardList',
      name: '办卡请求审批列表',
      component: RequestCardListPage,
      meta:{requireAuth: true, module:['notice'] }
    },
    {
      path: '/requestCardDetail/:cardId',
      name: '办卡请求审批详情',
      component: RequestCardDetailPage,
      meta:{requireAuth: true, module:['notice'] }
    },
    {
      path: '/requestKeepList',
      name: '存酒请求审批列表',
      component: RequestKeepListPage,
      meta:{requireAuth: true, module:['notice'] }
    },
    {
      path: '/requestKeepDetail/:keepId',
      name: '存酒请求审批详情',
      component: RequestKeepDetailPage,
      meta:{requireAuth: true, module:['notice'] }
    },
    {
      path: '/normalNoticeList',
      name: '一般消息列表',
      component: NormalNoticeListPage,
      meta:{requireAuth: true, module:['notice'] }
    },
    {
      path: '/normalNoticeDetail/:normalId',
      name: '一般消息详情',
      component: NormalNoticeDetailPage,
      meta:{requireAuth: true, module:['notice'] }
    },
    {
      path: '/todaySubscribeList',
      name: '今日预订列表',
      component: TodaySubscribeListPage,
      meta:{requireAuth: true, module:['todaySubscribe'] }
    },
    {
      path: '/distributeSubscribe/:subscribeId',
      name: '分配预订详情',
      component: DistributeSubscribePage,
      meta:{requireAuth: true, module:['todaySubscribe'] }
    },
    {
      path: '/subscribePerformance',
      name: '订台业绩',
      component: SubscribePerformancePage,
      meta:{requireAuth: true, module:['subscribePerformance'] }
    },
    {
      path: '/managerManager',
      name: '经理管理',
      component: ManagerManagerPage,
      meta:{requireAuth: true, module:['managerManager'] }
    },
    {
      path: '/nowAreaStatus',
      name: '当前场内状况',
      component: NowAreaStatusPage,
      meta:{requireAuth: true, module:['managerManager'] }
    },
    {
      path: '/nowSaleStatus',
      name: '当前场内销售状况',
      component: NowSaleStatusPage,
      meta:{requireAuth: true, module:['managerManager'] }
    },
    {
      path: '/turnOverList',
      name: '翻台列表',
      component: TurnOverListPage,
      meta:{requireAuth: true, module:['managerManager'] }
    }
  ]
})

router.beforeEach((to, from, next) => {//验证
  //console.log(to, from)
  setTimeout(()=>{
    store.commit('updateLoadingStatus', {isLoading: true})

    function requireAuth(){
      return new Promise(function(resolve, reject){
        if(to.meta.requireAuth) resolve()
        else reject({path:'',mess:'无需授权登录的页面'})
      })
    }
    function loginOrNot(){
      return new Promise(function(resolve, reject){
        //console.log('router index:',sessionStorage.getItem('index'))
        if (getLocalStorage('token_sales_index' + sessionStorage.getItem('index')) && getLocalStorage('userId_sales_index' + sessionStorage.getItem('index'))) resolve()
        else reject({path:'/login',mess:'登陆信息失效，请重新登陆，或关闭页面后重新进入系统'})
      })
    }
    function getAuthority(){
      return new Promise(function(resolve, reject){
        if(JSON.stringify(store.getters.getAuthority) != '{}')
          resolve()
        else
          store.dispatch('fetchAuthority',{callback:(status)=>{
              if(status == 'success'){
                resolve()
              }else if(status == 'error'){
                reject({path:'/login',mess:'用户未设置任何权限'})
              }
            }
          })
      })
    }
    function dispatchAuthority(){
      return new Promise(function(resolve, reject){
        let flag = false
        for(let authorityItem of store.getters.getAuthority.h5_saleHelper){//一级权限（模块权限）的判断
          if(typeof authorityItem == 'object') {
            for(var key in authorityItem) {
              if(to.meta.module)
                for(let moduleItem of to.meta.module){
                  if(key == moduleItem) flag = true
                }
            }
          } else if(typeof authorityItem == 'string') {
            if(to.meta.module)
              for(let moduleItem of to.meta.module){
                if(authorityItem == moduleItem) flag = true
              }
          }
        }
        if(flag || to.name == '主页' || to.name == '设置'){
          resolve()
        }else{
          reject({path:'/',mess:'没有权限查看该页面'})
        }
      })
    }

    requireAuth().then((mess)=>{
      return loginOrNot()
    }).then((mess)=>{
      return getAuthority()
    }).then((mess)=>{
      return dispatchAuthority()
    }).then((mess)=>{
      next()
    }).catch((data)=>{
      console.log(data.mess)
      if(data.path == '/login'){
        delLocalStorage('token_sales_index' + sessionStorage.getItem('index'))
        delLocalStorage('userId_sales_index' + sessionStorage.getItem('index'))
        clearvuex()
        store.commit('updateLoadingStatus', {isLoading: false})
        message({message:data.mess,type:'error'})
        next({path:'/login'})
      }else{
        if(data.path == '')next()
        else next(data.path)
      }
    })
  },1)
});

router.afterEach((to, from) => {//验证
/*
  store.commit('updateLoadingStatus', {isLoading: false})
*/
  if(from.path == '/login'){
  }
});

export default router
